$.views.settings.allowCode(true);
$.views.converters("getResponseModelName", function(val) {
	return getResponseModelName(val);
});

var template = $.templates("#template");
var tempBody = $.templates('#temp_body');
var tempBodyResponseModel = $.templates('#temp_body_response_model');

//获取context path
var contextPath = getContextPath();

function getContextPath() {
	var pathName = document.location.pathname;
	var index = pathName.substr(1).indexOf("/");
	var result = pathName.substr(0, index + 1);
	return result;
}

/**
 * @description 封装同步get请求,使用异步请求界面可能出现问题
 * @param url url地址
 * @param callBack 回调
 */
function get(url, callBack) {
	$.ajax({
		type: "get",
		url: url,
		async: false,
		success: function(data) {
			callBack(data);
		}
	});
}

/**
 * @description 初始化layui
 */
function initLayui(callBack) {
	layui.use(['layer', 'jquery', 'element', 'form'], function() {
		var $ = layui.jquery,
			layer = layui.layer,
			element = layui.element,
			form = layui.form;
		callBack();
	});
}

var globalGroups = [];

/**
    @description 获取分组信息
    @param callBack 回调
*/
function getGroups(callBack) {
	get("/swagger-resources", function(data) {
		globalGroups = data;
		callBack(data);
	}, "json");
}

function getGroupInfo(groupName) {
	get("/v2/api-docs?group=" + groupName, function(data) {

		//将groups加入data里面用于渲染
		data["groups"] = globalGroups;

		//设置标题
		$("#title").html(data.info.title);

		//设置数据
		$("body").html(template.render(data));
		$("#groups").val(groupName);
		var form = layui.form();
		form.render("select");
		var element = layui.element();
		element.init("nav");

		$("[name='a_path']").on("click",function() {
			var path = $(this).attr("path");
			var method = $(this).attr("method");
			var operationId = $(this).attr("operationId");
			$.each(data.paths[path], function(i, d) {
				if(d.operationId == operationId) {
					d.path = path;
					d.method = method;
					$("#path-body").html(tempBody.render(d));
					var modelName = getResponseModelName(d.responses["200"]["schema"]["$ref"]);
					if(modelName) {
						$("#path-body-response-model").html(tempBodyResponseModel.render(jsonData.definitions[modelName]));
					}
				}
			});
		});

		//提交测试按钮
		$("[name='btn_submit']").on("click",function() {
			var operationId = $(this).attr("operationId");
			var parameterJson = {};
			$("input[operationId='" + operationId + "']").each(function(index, domEle) {
				var k = $(domEle).attr("name");
				var v = $(domEle).val();
				parameterJson.push({
					k: v
				});
			});
		});
	}, "json");
}

$(function() {

	initLayui(function() {
		var form = layui.form();

		getGroups(function(data) {
			//首次默认加载第一个分组
			var firstGrpName = data[0].name;
			getGroupInfo(firstGrpName);
		});

		form.on("select(groups)", function(data) {
			getGroupInfo(data.value);
		});
	});

});

function getResponseModelName(val) {
	if(!val) {
		return null;
	}
	return val.substring(val.lastIndexOf("/") + 1, val.length);
}

//测试按钮，获取数据
function getData(operationId) {
	var path = contextPath + $("[m_operationId='" + operationId + "']").attr("path");
	//path 参数
	$("[p_operationId='" + operationId + "'][in='path']").each(function(index, domEle) {
		var k = $(domEle).attr("name");
		var v = $(domEle).val();
		if(v) {
			path = path.replace("{" + k + "}", v);
		}
	});

	//请求方式
	var parameterType = $("#content_type_" + operationId).val();

	//query 参数
	var parameterJson = {};
	if("form" == parameterType) {
		$("[p_operationId='" + operationId + "'][in='query']").each(function(index, domEle) {
			var k = $(domEle).attr("name");
			var v = $(domEle).val();
			if(v) {
				parameterJson[k] = v;
			}
		});
	} else if("json" == parameterType) {
		var str = $("#text_tp_" + operationId).val();
		try {
			parameterJson = JSON.parse(str);
		} catch(error) {
			layer.msg("" + error, {
				icon: 5
			});
			return false;
		}
	}

	//发送请求
	$.ajax({
		type: $("[m_operationId='" + operationId + "']").attr("method"),
		url: path,
		data: parameterJson,
		dataType: 'json',
		success: function(data) {
			var options = {
				withQuotes: true
			};
			$("#json-response").jsonViewer(data, options);
		}
	});
}

//请求类型
function changeParameterType(el) {
	var operationId = $(el).attr("operationId");
	var type = $(el).attr("type");
	$("#content_type_" + operationId).val(type);
	$(el).addClass("layui-btn-normal").removeClass("layui-btn-primary");
	if("form" == type) {
		$("#text_tp_" + operationId).hide();
		$("#table_tp_" + operationId).show();
		$("#pt_json_" + operationId).addClass("layui-btn-primary").removeClass("layui-btn-normal");
	} else if("json" == type) {
		$("#text_tp_" + operationId).show();
		$("#table_tp_" + operationId).hide();
		$("#pt_form_" + operationId).addClass("layui-btn-primary").removeClass("layui-btn-normal");
	}
}